import pygame
import sys
import os
from db_manager import DatabaseManager

class LoginScreen:
    def __init__(self, game):
        self.game = game
        self.screen = game.screen
        self.width = game.width
        self.height = game.height
        
        # 初始化数据库管理器
        self.db_manager = game.db_manager
        self.db_connected = hasattr(self.db_manager, 'connection') and self.db_manager.connection is not None and self.db_manager.connection.is_connected()
        
        # 状态消息
        self.status_message = ""
        self.status_color = (0, 0, 0)
        self.status_timer = 0
        
        # 如果数据库未连接，显示离线模式消息
        if not self.db_connected:
            self.show_status("数据库未连接，使用离线模式", (255, 140, 0))
        
        # 颜色定义
        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.gray = (230, 230, 230)
        self.light_gray = (240, 240, 240)
        self.apple_blue = (0, 122, 255)
        self.apple_light_blue = (88, 172, 255)
        self.apple_red = (255, 59, 48)
        self.apple_green = (52, 199, 89)
        self.apple_orange = (255, 140, 0)
        
        # 字体
        pygame.font.init()
        FONT_PATH = 'C:\\Windows\\Fonts\\simsun.ttc'
        try:
            self.title_font = pygame.font.Font(FONT_PATH, 60)
            self.button_font = pygame.font.Font(FONT_PATH, 36)
            self.input_font = pygame.font.Font(FONT_PATH, 32)
            self.info_font = pygame.font.Font(FONT_PATH, 24)
            self.status_font = pygame.font.Font(FONT_PATH, 20)
        except:
            print("字体加载失败")
        
        # 用户名输入框 
        self.username_rect = pygame.Rect(self.width//2 - 150, self.height//2 - 100, 300, 50)
        self.username_text = ""
        self.username_active = False
        
        # 密码输入框 
        self.password_rect = pygame.Rect(self.width//2 - 150, self.height//2, 300, 50)
        self.password_text = ""
        self.password_active = False
        self.show_password = False  # 不显示密码
        
        # 登录按钮
        self.login_rect = pygame.Rect(self.width//2 - 150, self.height//2 + 100, 140, 50)
        self.login_text = "登录"
        
        # 注册按钮
        self.register_rect = pygame.Rect(self.width//2 + 10, self.height//2 + 100, 140, 50)
        self.register_text = "注册"
        
        # 当前活动状态（登录或注册）
        self.is_registering = False
        
        # 加载背景图片
        self.background = None
        try:
            bg_path = os.path.join("img", "background.jpg")
            if os.path.exists(bg_path):
                self.background = pygame.image.load(bg_path)
                self.background = pygame.transform.scale(self.background, (self.width, self.height))
        except:
            pass
        
        # 加载音效
        self.click_sound = None
        try:
            sound_path = os.path.join("sound", "down.mp3")
            if os.path.exists(sound_path):
                self.click_sound = pygame.mixer.Sound(sound_path)
        except:
            pass
        
        # 启用文本输入
        pygame.key.set_repeat(500, 50)  # 设置按键重复
        
        print("登录界面初始化完成，输入框已设置")
    
    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 用户名输入框点击
            if self.username_rect.collidepoint(event.pos):
                self.username_active = True
                self.password_active = False
                # print("激活用户名输入框")
            # 密码输入框点击
            elif self.password_rect.collidepoint(event.pos):
                self.username_active = False
                self.password_active = True
                # print("激活密码输入框")
            else:
                self.username_active = False
                self.password_active = False
            
            # 登录按钮点击
            if self.login_rect.collidepoint(event.pos):
                if self.click_sound:
                    self.click_sound.play()
                if self.username_text.strip() and self.password_text.strip():  # 确保用户名和密码不为空
                    self.login()
            
            # 注册按钮点击
            elif self.register_rect.collidepoint(event.pos):
                if self.click_sound:
                    self.click_sound.play()
                self.is_registering = not self.is_registering
                if self.is_registering:
                    self.login_text = "确认"
                    self.register_text = "返回"
                else:
                    self.login_text = "登录"
                    self.register_text = "注册"
        
        # 处理键盘输入
        elif event.type == pygame.KEYDOWN:
            # 用户名输入框处理
            if self.username_active:
                if event.key == pygame.K_RETURN:
                    self.username_active = False
                    self.password_active = True
                    # print("按下回车键，切换到密码输入框")
                elif event.key == pygame.K_BACKSPACE:
                    self.username_text = self.username_text[:-1]
                    # print(f"删除字符，当前用户名: {self.username_text}")
                elif event.key == pygame.K_TAB:
                    self.username_active = False
                    self.password_active = True
                    # print("按下Tab键，切换到密码输入框")
                else:
                    # 输入字符
                    if event.unicode and len(self.username_text) < 15 and event.unicode.isprintable():
                        self.username_text += event.unicode
                        
            
            # 密码输入框处理
            elif self.password_active:
                if event.key == pygame.K_RETURN:
                    if self.username_text.strip() and self.password_text.strip():
                        # print("按下回车键，尝试登录")
                        self.login()
                elif event.key == pygame.K_BACKSPACE:
                    self.password_text = self.password_text[:-1]
                    # print("删除密码字符")
                elif event.key == pygame.K_TAB:
                    self.username_active = True
                    self.password_active = False
                    # print("按下Tab键，切换到用户名输入框")
                else:
                    # 使用event.unicode处理所有可打印字符的输入
                    if event.unicode and len(self.password_text) < 20 and event.unicode.isprintable():
                        self.password_text += event.unicode
                        # print("添加密码字符")
    
    def show_status(self, message, color=(0, 0, 0)):
        """显示状态消息"""
        self.status_message = message
        self.status_color = color
        self.status_timer = 180  # 显示3秒（60帧/秒）
        print(f"状态消息: {message}")
    
    def login(self):
        """处理登录或注册逻辑"""
        # 如果数据库未连接，直接使用离线模式
        if not self.db_connected:
            self.show_status("离线模式：直接进入游戏", self.apple_orange)
            self.game.set_username(self.username_text)
            pygame.time.delay(1000)
            self.game.switch_to_menu()
            return
            
        if self.is_registering:
            # 注册新用户
            success, message = self.db_manager.register_user(self.username_text, self.password_text)
            if success:
                self.show_status("注册成功！正在登录...", self.apple_green)
                self.game.set_username(self.username_text)
                # 延迟切换到菜单界面，让用户看到成功消息
                pygame.time.delay(1000)
                self.game.switch_to_menu()
            else:
                self.show_status(message, self.apple_red)
        else:
            # 验证登录
            if self.db_manager.verify_login(self.username_text, self.password_text):
                self.show_status("登录成功！", self.apple_green)
                self.game.set_username(self.username_text)
                # 延迟切换到菜单界面，让用户看到成功消息
                pygame.time.delay(1000)
                self.game.switch_to_menu()
            else:
                self.show_status("用户名或密码错误！", self.apple_red)
    
    def render(self):
        # 绘制背景
        if self.background:
            self.screen.blit(self.background, (0, 0))
        else:
            for y in range(self.height):
                # 从顶部的浅灰色渐变到底部的白色
                color = (
                    int(self.light_gray[0] * (1 - y/self.height) + self.white[0] * (y/self.height)),
                    int(self.light_gray[1] * (1 - y/self.height) + self.white[1] * (y/self.height)),
                    int(self.light_gray[2] * (1 - y/self.height) + self.white[2] * (y/self.height))
                )
                pygame.draw.line(self.screen, color, (0, y), (self.width, y))
        
        # 绘制标题 - 调整位置
        title_text = self.title_font.render("五子棋", True, self.black)
        title_rect = title_text.get_rect(center=(self.width//2, self.height//2 - 200))
        self.screen.blit(title_text, title_rect)
        
        # 注册模式下显示副标题
        if self.is_registering:
            subtitle_text = self.button_font.render("创建新账户", True, (80, 80, 80))
            subtitle_rect = subtitle_text.get_rect(center=(self.width//2, self.height//2 - 150))
            self.screen.blit(subtitle_text, subtitle_rect)
        
        # 绘制用户名标签 - 调整位置和样式
        username_label = self.info_font.render("用户名", True, (80, 80, 80))
        label_rect = username_label.get_rect(x=self.username_rect.x, bottom=self.username_rect.y - 10)
        self.screen.blit(username_label, label_rect)
        
        # 绘制用户名输入框
        username_color = self.apple_blue if self.username_active else self.gray
        pygame.draw.rect(self.screen, self.white, self.username_rect, 0, 10)  # 填充
        pygame.draw.rect(self.screen, username_color, self.username_rect, 2, 10)  # 边框
        
        # 绘制用户名文本
        username_surface = self.input_font.render(self.username_text, True, self.black)
        username_text_rect = username_surface.get_rect()
        username_text_rect.center = self.username_rect.center
        
        # 如果用户名为空，显示占位符 - 使用更浅的颜色
        if not self.username_text:
            username_placeholder = self.input_font.render("请输入用户名", True, (200, 200, 200))
            username_placeholder_rect = username_placeholder.get_rect(left=self.username_rect.x + 15, centery=self.username_rect.centery)
            self.screen.blit(username_placeholder, username_placeholder_rect)
        else:
            # 文本左对齐显示
            username_text_rect.left = self.username_rect.left + 15
            username_text_rect.centery = self.username_rect.centery
            self.screen.blit(username_surface, username_text_rect)
        
        # 绘制密码标签 - 调整位置和样式
        password_label = self.info_font.render("密码", True, (80, 80, 80))
        label_rect = password_label.get_rect(x=self.password_rect.x, bottom=self.password_rect.y - 10)
        self.screen.blit(password_label, label_rect)
        
        # 绘制密码输入框
        password_color = self.apple_blue if self.password_active else self.gray
        pygame.draw.rect(self.screen, self.white, self.password_rect, 0, 10)  # 填充
        pygame.draw.rect(self.screen, password_color, self.password_rect, 2, 10)  # 边框
        
        # 绘制密码文本（显示为*号）
        display_password = '*' * len(self.password_text) if not self.show_password else self.password_text
        password_surface = self.input_font.render(display_password, True, self.black)
        password_text_rect = password_surface.get_rect()
        password_text_rect.center = self.password_rect.center
        
        # 如果密码为空，显示占位符 - 使用更浅的颜色
        if not self.password_text:
            password_placeholder = self.input_font.render("请输入密码", True, (200, 200, 200))
            password_placeholder_rect = password_placeholder.get_rect(left=self.password_rect.x + 15, centery=self.password_rect.centery)
            self.screen.blit(password_placeholder, password_placeholder_rect)
        else:
            # 文本左对齐显示
            password_text_rect.left = self.password_rect.left + 15
            password_text_rect.centery = self.password_rect.centery
            self.screen.blit(password_surface, password_text_rect)
        
        # 绘制登录按钮
        login_color = self.apple_blue
        hover_color = self.apple_light_blue
        
        # 检查鼠标是否悬停在登录按钮上
        mouse_pos = pygame.mouse.get_pos()
        if self.login_rect.collidepoint(mouse_pos):
            pygame.draw.rect(self.screen, hover_color, self.login_rect, 0, 10)
        else:
            pygame.draw.rect(self.screen, login_color, self.login_rect, 0, 10)
        
        # 绘制登录按钮文本
        login_text = self.button_font.render(self.login_text, True, self.white)
        login_text_rect = login_text.get_rect(center=self.login_rect.center)
        self.screen.blit(login_text, login_text_rect)
        
        # 绘制注册按钮
        register_color = (100, 100, 100)  # 灰色按钮
        register_hover_color = (130, 130, 130)
        
        # 检查鼠标是否悬停在注册按钮上
        if self.register_rect.collidepoint(mouse_pos):
            pygame.draw.rect(self.screen, register_hover_color, self.register_rect, 0, 10)
        else:
            pygame.draw.rect(self.screen, register_color, self.register_rect, 0, 10)
        
        # 绘制注册按钮文本
        register_text = self.button_font.render(self.register_text, True, self.white)
        register_text_rect = register_text.get_rect(center=self.register_rect.center)
        self.screen.blit(register_text, register_text_rect)
        
        # 显示状态消息
        if self.status_message and self.status_timer > 0:
            status_text = self.status_font.render(self.status_message, True, self.status_color)
            status_rect = status_text.get_rect(center=(self.width//2, self.height//2 + 170))
            self.screen.blit(status_text, status_rect)
            self.status_timer -= 1
        
        # 绘制底部版权信息 - 调整位置，确保不会与其他元素重叠
        try:
            footer_font = pygame.font.Font(FONT_PATH, 18)
        except:
            footer_font = pygame.font.SysFont("simsun", 18)
        footer_text = footer_font.render("© 2025 五子棋游戏", True, (150, 150, 150))
        footer_rect = footer_text.get_rect(center=(self.width//2, self.height - 20))
        self.screen.blit(footer_text, footer_rect) 